package controller;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.Random;

@WebServlet("/Login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取当前用户会话
        HttpSession session = request.getSession();
        session.setMaxInactiveInterval(24 * 3600);

        String user = request.getParameter("username");
        if (user == null) {
            // 遍历客户端存储的cookie
            Cookie[] cookies = request.getCookies();
            for (Cookie cookie : cookies) {
                if ("user".equals(cookie.getName())) {
                    user = cookie.getValue();
                    doLogin(request, response, session, user);
                }
            }
            RequestDispatcher view = request.getRequestDispatcher(response.encodeURL("login.jsp"));
            view.forward(request, response);

        }else {
            // 执行登录操作
            Cookie cookie = new Cookie("user", user);
            // 设置cookie的生存时间，默认情况下cookie在会话结束时释放
            cookie.setMaxAge(7 * 24 * 3600);
            // 将cookie返回客户端
            response.addCookie(cookie);
            doLogin(request, response, session, user);
        }
    }

    private void doLogin(HttpServletRequest request, HttpServletResponse response, HttpSession session, String user) throws ServletException, IOException {
        // 将用户名加入session会话
        session.setAttribute("user", user);
        // 将随机数加入session会话
        Integer real = (Integer) session.getAttribute("real");
        if (real == null) {
            real = new Random().nextInt(100)+1;
            session.setAttribute("real", real);

            // 将随机数存入cookie
            Cookie cookie = new Cookie("real", real.toString());
            cookie.setMaxAge(7 * 24 * 3600);
            response.addCookie(cookie);
        }

        // 跳转到主页面
        RequestDispatcher view = request.getRequestDispatcher(response.encodeURL("home.jsp"));
        view.forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
